<template>
  <div class="app-container">
    <!--    新增操作-->
    <el-row class="mb20 mb20">
      <el-button
        class="el-icon-plus"
        @click="handleAddUser"
        type="primary"
      >新增客户端
      </el-button>
      <el-button
        class="el-icon-refresh"
        @click="getListData">
        刷新
      </el-button>
      <el-button
        class="el-icon-refresh"
        @click="clearCache">
        清除MerchantWords缓存
      </el-button>
      <el-button
        class="el-icon-s-promotion"
        @click="handlerConfigServer">
        节点配置
      </el-button>
    </el-row>
    <!--    列表-->
    <el-row :gutter="20">
      <el-col v-for="(item, index) in list" :key="index" :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
        <el-card :body-style="{ padding: '0px' }" class="box-card">
          <!-- 头部-->
          <div slot="header" class="clearfix">
            <span>
              <i class="el-icon-s-claim">
                <span>{{item.name}}</span>
              </i>
            </span>
          </div>
          <!--内容-->
          <div class="backImg">
            <img style="width: 50%;height: 100%" :src="logoUrl + item.logo">
            <div>
              <span style="color: #f8ac59" class="mb10" :title="item.url">{{item.url}}</span>
              <span>在线人数:<span style="color: #4CE54C">{{item.users}}人</span></span>
            </div>
          </div>
          <!--操作-->
          <div class="card-footer">
            <el-button
              class="el-icon-folder"
              @click="toUserAdmin(item)"
              type="primary">
              内置账户管理
            </el-button>
            <el-button
              class="el-icon-edit"
              @click="toUpdateAdmin(item)"
              type="success">
              修改
            </el-button>
            <el-button
              class="el-icon-delete"
              @click="toDeleteAdmin(item)"
              type="info">
              删除
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!--  新增弹框客户端-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
               v-if="dialogVisible">
        <el-form-item label="客户端名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="客户端地址" prop="url">
          <el-input v-model="ruleForm.url"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="logo">
          <el-row>
            <el-col :span="15">
              <input type="file" ref="inputer" class="face" accept="image/*" @change="uploadPic"></input>
            </el-col>
            <!--            <span>{{ruleForm.logo}}</span>-->
          </el-row>
          <!--  <el-row v-if="title === '修改客户端'">
              <el-col :span="24">
                <span>{{ruleForm.logo? ruleForm.logo.slice(27): ''}}</span>
              </el-col>

            </el-row>-->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancle">取 消</el-button>
    <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
  </span>
    </el-dialog>

    <!--服务节点选择弹框-->
    <el-dialog
      :title="title"
      :visible.sync="serverConfigDialogVisible"
      width="30%"
    >
      <el-radio-group v-model="serverNode">
        <el-radio
          v-for="item in serverList"
          :key="item.id"
          :value="item.id"
          :label="item.serverName"
        >{{item.serverName}}({{item.ip}})</el-radio>
      </el-radio-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="serverConfigCancel">取 消</el-button>
      <el-button type="primary" @click="serverConfigSubmit">确 定</el-button>
    </span>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getListData"/>

  </div>
</template>

<script>
  import {getToken} from '@/utils/auth'
  import {listData, deleAdmin, clearCache} from '@/api/index/index'
  import {getServerList,enable} from "@/api/serverConfig/index"

  const defaultSettings = require('@/settings.js')
  export default {
    name: "index",
    data() {

      const baseUrl =
        process.env.NODE_ENV === 'development'
          ? process.env.VUE_APP_BASE_API
          : defaultSettings.target

      return {

        isShowPic: '',

        title: '',

        dialogImageUrl: '', //本地回显

        total: 0,

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },

        logoUrl: baseUrl,
        url: baseUrl + '/client-products',
        upDateurl: baseUrl + '/client-products',
        showSearch: true,
        dialogVisible: false,
        serverConfigDialogVisible: false,
        list: [], //列表信息
        ruleForm: {
          name: '',
          url: '',
          logo: null,
          description: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入客户端名称', trigger: 'blur'},
          ],
          url: [
            {required: true, message: '请输入客户端地址', trigger: 'blur'},
          ],
          logo: [
            {required: true, message: '请选择logo图片', trigger: 'blur'},
          ],
        },
        serverNode: 1,
        serverList:[]
      }
    },
    mounted() {
      this.getListData()
    },
    methods: {
      // 删除
      toDeleteAdmin(item) {
        this.$confirm(
          '是否确认删除数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            deleAdmin(item.id).then(resp => {
              let {code} = resp
              if (code === 200) {
                this.getListData()
                this.msgSuccess("删除成功");
              }
            })
          })
          .catch(function () {
          });


      },
      cancle() {
        // this.$refs['ruleForm'].resetFields();
        // this.resetForm()
        this.ruleForm = {
          name: '',
          url: '',
          logo: null,
          description: ''
        }
        // this.ruleForm.logo = null
        this.dialogVisible = false
      },
      serverConfigCancel(){
        this.serverConfigDialogVisible = false;
      },
      selectedNode(e){
        console.dir(e);
      },
      serverConfigSubmit(){
        let id;
        //获取选择的id
        for(let value of this.serverList){
          if(value.serverName == this.serverNode){
            id = value.id
          }
        }
        let params = {
          id:id
        }
        enable(params).then(resp => {
          let {code} = resp
          if(code == 200){
            this.$message({
              message:'修改成功',
              type:'success'
            })
          }else{
            this.$message({
              message:"修改失败",
              type:'error'
            })
          }
          this.serverConfigDialogVisible = false;
        })
      },
      uploadPic(value) {
        let inputDOM = this.$refs.inputer;
        let file = inputDOM.files;
        this.isShowPic = file
        /*this.dialogImageUrl = file.url;
        this.dialogImageUrl = new window.File([this.dialogImageUrl], file.name, {
          type: file.type
        });*/

        console.log(file[0], '==========')
        this.ruleForm.logo = file[0]
        console.log(this.ruleForm.logo, '？？？？')

      },
      //跳转至内置账户管理页面
      toUserAdmin(parms) {
        let {id} = parms
        this.$router.push({path: '/system/setClient', query: {productId: id, productName: parms.name}})
      },
      //关闭弹框
      handleClose(done) {
        done();
      },
      //新增客户端
      handleAddUser() {
        this.dialogVisible = true
        this.title = '新增客户端'
      },
      handlerConfigServer() {
        //获取数据
        getServerList().then((resp) => {
          let {code, rows, total} = resp
          if(code === 0){
            this.serverList = rows;
            //选中
            for(let value of this.serverList){
              if(value.status == 1){
                this.serverNode = value.serverName;
                break;
              }
            }
            this.serverConfigDialogVisible = true;
            this.title = "服务器节点选择";
          }else{
            this.$message({
              message: '获取服务器节点失败',
              type: 'error'
            })
          }
        });

      },
      //修改客户端
      toUpdateAdmin(item) {
        console.log(item, '???')
        this.dialogVisible = true
        this.title = '修改客户端'
        this.ruleForm = item
      },
      //新增提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.title === '新增客户端') {
              let {name, url, description, logo} = this.ruleForm
              let formData = new FormData()
              formData.append('logo', logo)
              formData.append('name', name)
              formData.append('url', url)
              formData.append('description', description)

              this.toAddManager(formData)
            } else {
              let {name, url, id, description, logo} = this.ruleForm
              let formData = new FormData()
              console.log(typeof logo, '----------')
              if (typeof logo !== 'string') {
                formData.append('logo', logo)
              }
              formData.append('name', name)
              formData.append('url', url)
              formData.append('description', description)
              formData.append('id', id)
              this.toUpdateManager(formData)
            }

            this.resetForm(formName)
            this.resetForm.logo = null
            this.dialogVisible = false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //  获取列表
      getListData() {
        let {pageSize, pageNum} = this.queryParams
        let parms = {pageable: true, pageSize: pageSize, pageNum: pageNum}
        listData(parms).then(resp => {
          let {code, rows, total} = resp
          if (code === 200) {
            this.list = rows
            this.total = total
          }
        })
      },
      clearCache() {
        clearCache().then(resp => {
          let {code} = resp;
          if (code === 200) {
            this.$message({
              message: '清理成功',
              type: 'success'
            });
          }
        })
      },
      //  新增
      toAddManager(formData) {
        this.axios.post(this.url,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data;',
              'Authorization': 'Bearer ' + getToken(),
              'X-User-System-ID': 'SYS_USER'
            }
          }
        )
          .then(resp => {
            let {code, msg} = resp.data
            if (code === 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.getListData()
            } else {
              this.$message.error(msg);
            }
          })
          .catch(err => {
            console.log(err)
          })
      },
      //  修改
      toUpdateManager(formData) {
        this.axios.put(this.upDateurl,
          formData,
          {
            method: 'put',
            headers: {
              'Content-Type': 'multipart/form-data;',
              'Authorization': 'Bearer ' + getToken(),
              'X-User-System-ID': 'SYS_USER'
            }
          }
        )
          .then(resp => {
            let {code, msg} = resp.data
            if (code === 200) {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.getListData()
            } else {
              this.$message.error(msg);
            }
          })
          .catch(err => {
            console.log(err)
          })
      },
    }
  }
</script>

<style scoped>
  .backImg {
    height: 150px;
    display: flex;
    border-bottom: 1px solid #E6EBF5;
  }

  .backImg > div:first-child {
    height: 100%;
    width: 100px;
    background: url("../assets/back.jpg") no-repeat center center;
    background-size: 100% 100%;
  }

  .backImg > div:last-child {
    width: 50%;
    display: flex;
    flex-direction: column;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word;
    justify-content: center;
  }

  .el-icon-s-claim {
    color: #1c84c6;
  }

  .el-icon-s-claim > span {
    display: inline-block;
    padding-left: 10px;
  }

  .card-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 60px;
    flex-wrap: wrap;
  }
</style>
